<?php
/**
 * Created by PhpStorm.
 * User: LYQ
 * Date: 2019/8/26
 * Time: 18:54
 */

namespace app\api\controller;


use app\api\model\LoginModel;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\Base as bs;
class Login
{
    public function rest(){
        $request = Request::instance();
        $method = $request->method();
        switch ($method){
            case 'GET':
                $this->getUser();
                break;
            case 'POST':
                $this->login();
                break;
            case 'PUT':
                $this->userEdit();
                break;
        }
    }

    public function login(){
        $username = I('username');
        $studentNumber = I('student_number');
        $password = I('password');
        if(!empty($username)){
            $getData = Db::table('user')->where(['username'=>$username,'password'=>user_md5($password)])->field('id,username,permissions')->find();
        }else{
            $getData = Db::table('user')->where(['student_number'=>$studentNumber,'password'=>user_md5($password)])->field('id,username,permissions')->find();
        }
        if($getData){
            $admin = Db::table('user')->where(['id'=>$getData['id']])->update(['token'=>getToken($getData['username'],$getData['permissions']),'update_time'=>time(),'expiration_time'=>time()+1200]);
            $admin ? 'true':'false';
            $data = Db::table('user')->field('id,username,update_time,token,permissions')->where(['id'=>$getData['id']])->find();
        }else{
            $this->apiReturn(303,'账号或者密码错误');
        }
        $this->apiReturn(200,'登录成功',$data,0);


    }

    public function apiReturn( $code=200 , $msg='', $data = array() ,$total=0 ){
        $returnData = array(
            'code' => $code,
            'msg'  => $msg?$msg:return_msg($code),
            'data' => $data,
            'total'=> $total
        );
        if(I('callback')){
            echo I('callback').'('.json_encode($returnData).')';die;
        }
        echo json_encode($returnData);die;
    }
}